package com.isman.placeslist;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isman.placeslist.apiobject.Session;
import com.isman.placeslist.apiobject.SingUp;
import com.isman.placeslist.fb.FacebookClient;
import com.isman.placeslist.setting.ProjectPref;
import com.isman.placeslist.ws.AsyncRunnerHeadler;
import com.isman.placeslist.ws.ServiceProvider;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

public class PageChoine extends Activity {
	public static final int SINGUP_WITH_EMAIL = 0;
	public static final int SINGUP_WITH_FB = 1;
	public static final int SINGIN = 2;

	public static final int DIALOG_WITH_FACEBOOK = 0;
	public static final int DIALOG_WITHOUT_FACEBOOK = 1;

	private Session mSingIn;
	private Facebook mFacebook;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.page_choine);

		
		
		vImgLogo = (ImageView) findViewById(R.id.img_choine_logo);
		vBtnSingIn = (Button) findViewById(R.id.btn_choine_singin);
		vBtnSingUp = (Button) findViewById(R.id.btn_choine_with_email);
		vBtnSingUpWithFb = (Button) findViewById(R.id.btn_choine_with_fb);

		vBtnSingIn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivityForResult(new Intent(PageChoine.this,
						PageSingin.class), SINGIN);
			}
		});
		vBtnSingUp.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivityForResult(new Intent(PageChoine.this,
						PageSingup.class), SINGUP_WITH_EMAIL);
			}
		});
		vBtnSingUpWithFb.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mFbSingIn();
			}
		});
		vImgLogo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String url = "http://www.placeslist.com/";
				Intent i = new Intent(Intent.ACTION_VIEW);
				i.setData(Uri.parse(url));
				startActivity(i);
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(mFacebook !=null)mFacebook.authorizeCallback(requestCode, resultCode, data);
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case SINGIN:
				setResult(Activity.RESULT_OK, data);
				finish();
				break;
			case SINGUP_WITH_EMAIL:
				setResult(Activity.RESULT_OK, data);
				finish();
				break;
			case SINGUP_WITH_FB:
				SingUp singup = (SingUp) data.getExtras().getSerializable(
						PageConfirm.SINGUP_INFO);
				mSingupWithFacebook(singup);
				break;
			}
		}
	}

	protected void mFbSingIn() {
		FacebookClient client = new FacebookClient(this);
		mFacebook = client.getFacebook();
		mFacebook.authorize(this, new DialogListener() {

			@Override
			public void onFacebookError(FacebookError e) {
				Toast.makeText(getApplicationContext(), e.toString(), 0).show();

			}

			@Override
			public void onError(DialogError e) {
				Toast.makeText(getApplicationContext(), e.toString(), 0).show();

			}

			@Override
			public void onComplete(Bundle values) {
				mFbDetail();
			}

			@Override
			public void onCancel() {
				Toast.makeText(getApplicationContext(), "cancel", 0).show();

			}
		});
	}

	protected void mFbDetail() {
		ProjectPref.saveFbSession(mFacebook, this);
		AsyncFacebookRunner runner = new AsyncFacebookRunner(mFacebook);
		runner.request("/me", new RequestListener() {

			@Override
			public void onMalformedURLException(MalformedURLException e,
					Object state) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onIOException(IOException e, Object state) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onFileNotFoundException(FileNotFoundException e,
					Object state) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onFacebookError(FacebookError e, Object state) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onComplete(String response, Object state) {
				final SingUp singUp = new Gson().fromJson(response,
						SingUp.class);
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						singUp.setFromWith(SingUp.FROM_WITH_FB);
						mCheckFacebook(singUp);
					}
				});
			}
		});
	}

	protected void mCheckFacebook(final SingUp singUp) {
		ServiceProvider provider = new ServiceProvider(this);
		provider.ChechFacebook(singUp.getEmail(), singUp.getId(),
				new AsyncRunnerHeadler() {
					@Override
					public void onError(final int statusCode, final String json) {
						Log.i("TAG Error", json);
						runOnUiThread(new Runnable() {
							@Override 
							public void run() {
								if (statusCode == 402) {
									Intent intent = new Intent(PageChoine.this,
											PageConfirm.class);
									intent.putExtra(PageConfirm.SINGUP_INFO,
											singUp);
									startActivityForResult(intent,
											SINGUP_WITH_FB);
								} else if (statusCode == 403) {
									Toast.makeText(PageChoine.this,
											"this email cannot singup",
											Toast.LENGTH_LONG).show();
								}
							}
						});
					}

					@Override
					public void onConnectingError(final String message) {
						Log.i("TAG C Error", message);
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								Toast.makeText(PageChoine.this,
										"ConnectingError" + message,
										Toast.LENGTH_LONG).show();
							}
						});
					}

					@Override
					public void onComplete(final String json) {
						Log.i("TAG Com", json);
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								try {
									mSingIn = new Gson().fromJson(json, Session.class);
									if (mSingIn.getResultType() == 0) {
										showDialog(DIALOG_WITHOUT_FACEBOOK);
									}else if(mSingIn.getResultType() == 1){
										showDialog(DIALOG_WITH_FACEBOOK);
									}
								} catch (JsonSyntaxException e) {
									e.printStackTrace();
								}
							}
						});
					}

					@Override
					public void onAuthenticate(final String json) {
						Log.i("TAG Auth", json);
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								Toast.makeText(PageChoine.this, "Auth " + json,
										Toast.LENGTH_LONG).show();
							}
						});
					}
				});
	}

	protected void mSingupWithFacebook(SingUp singup) {
		mDialog = ProgressDialog.show(PageChoine.this, "", "Singing Up");
		ServiceProvider provider = new ServiceProvider(PageChoine.this);
		provider.SingUpWithFacebook(singup, new AsyncRunnerHeadler() {
			@Override
			public void onError(final int statusCode, final String json) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						mDialog.cancel();
						Toast.makeText(PageChoine.this,
								"Error " + statusCode + "  " + json,
								Toast.LENGTH_LONG).show();
					}
				});
			}

			@Override
			public void onConnectingError(final String json) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						mDialog.cancel();
						Toast.makeText(PageChoine.this,
								"ConnectingError" + json, Toast.LENGTH_LONG)
								.show();
					}
				});
			}

			@Override
			public void onComplete(final String json) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						mDialog.cancel();
						Intent intent = new Intent();
						try {
							Session singin = new Gson().fromJson(json,
									Session.class);
							intent.putExtra(PageMain.SINGIN_INFO, singin);
						} catch (JsonSyntaxException e) {
							e.printStackTrace();
						}
						setResult(Activity.RESULT_OK, intent);
						finish();
					}
				});
			}

			@Override
			public void onAuthenticate(final String json) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						mDialog.cancel();
						Log.d("Singup", json);
						Toast.makeText(PageChoine.this, "Authenticate " + json,
								Toast.LENGTH_LONG).show();
					}
				});
			}
		});
	}

	private ProgressDialog mDialog;

	private ImageView vImgLogo;
	private Button vBtnSingIn;
	private Button vBtnSingUp;
	private Button vBtnSingUpWithFb;

	@Override
	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder;
		switch (id) {
		case DIALOG_WITH_FACEBOOK:
			builder = new AlertDialog.Builder(this);
			builder.setMessage("ผู้ใช้นี้มีระบบเเล้ว ระบบจะ Login อัตโนมัติ")
			       .setCancelable(false)
			       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
							Intent intent = new Intent();
							intent.putExtra(PageMain.SINGIN_INFO, mSingIn);
							setResult(RESULT_OK, intent);
							finish();
			           }
			       });
			return builder.create();
		case DIALOG_WITHOUT_FACEBOOK:
			builder = new AlertDialog.Builder(this);
			builder.setMessage("ผู้ใช้นี้มีระบบเเล้ว ระบบจะ Login ให้อัตโนมัติ")
			       .setCancelable(false)
			       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
							Intent intent = new Intent();
							intent.putExtra(PageMain.SINGIN_INFO, mSingIn);
							setResult(RESULT_OK, intent);
							finish();
			           }
			       });
			return builder.create();
		}
		return null;
	}
}
